<!-- 自定义鼠标右击出现菜单 -->
<script setup lang="ts">
import {ref} from "vue";
import useContextMenu from "./useContextMenu.ts";

const containerRef = ref(null);
const {x, y, showMenu} = useContextMenu(containerRef)

function handleClick(item: any) {
  // 菜单选中后关闭菜单
  showMenu.value = false
  // 并返回选中的菜单
  emit('select', item)
}

function handleBeforeEnter(el: any) {
  el.style.height = 0
}

function handleEnter(el: any) {
  el.style.height = 'auto'
  const h = el.clientHeight
  el.style.height = 0
  requestAnimationFrame(() => {
    el.style.height = h + 'px'
    el.style.transition = '.5s'
  })
}

function handleAfterEnter(el: any) {
  el.style.transition = 'none'
}

const props = defineProps({
  menu: {
    type: Array,
    default: () => []
  }
})
// 选中菜单项时返回数据
const emit = defineEmits(['select'])

</script>

<template>
  <div ref="containerRef">
    <slot></slot>
    <!-- 通过Teleport将菜单放置在body中，这样就可以在任何位置右击出现菜单了 -->
    <Teleport to="body">
      <!-- 使用 Transition 组件，并注册 beforeEnter 和 enter 事件  -->
      <transition appear @before-enter="handleBeforeEnter" @enter="handleEnter" @after-enter="handleAfterEnter">
        <!-- 菜单显示区域 -->
        <div class="context-menu" v-if="showMenu" :style="{left: x + 'px',top: y + 'px'}">
          <div class="menu-list">
            <div
                class="menu-item"
                @click="handleClick(item)"
                v-for="(item,index) in menu"
                :key="index"
            >
              <div class="menu-context">
                <el-icon class="menu-icon">
                  <component :is="item.icon"></component>
                </el-icon>
                <span class="menu-text">
                {{ item.label }}
              </span>
              </div>
            </div>
          </div>
        </div>
      </transition>
    </Teleport>
  </div>
</template>

<style scoped lang="scss">
.context-menu {
  position: fixed;
  top: 0;
  left: 0;

  .menu-list {
    padding: 4px;
    background: #fff;
    box-shadow: 3px 3px 3px #807f7f;
    border-radius: 5px;
    min-width: 160px;

    .menu-item {
      line-height: 30px;
      font-size: 16px;
      text-align: left;
      width: 100%;
      border-radius: 5px;

      .menu-context {
        margin: 4px 10px;

        .menu-icon {
          vertical-align: middle;
          font-size: 18px;
        }

        .menu-text {
          margin-left: 10px;
        }
      }
    }

    .menu-item:hover {
      background-color: #F5F5F6;
    }
  }
}
</style>
